package org.jeecg.modules.shop.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import net.sf.ezmorph.object.MapToDateMorpher;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.shop.entity.ScSystemShop;
import org.jeecg.modules.shop.mapper.ScSystemShopMapper;
import org.jeecg.modules.shop.service.IScSystemShopService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.model.SysDepartTreeModel;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: sc_system_shop
 * @Author: jeecg-boot
 * @Date: 2021-10-31
 * @Version: V1.0
 */
@Api(tags = "sc_system_shop")
@RestController
@RequestMapping("/shop/scSystemShop")
@Slf4j
public class ScSystemShopController extends JeecgController<ScSystemShop, IScSystemShopService> {
    @Autowired
    private IScSystemShopService scSystemShopService;
    @Resource
    private ScSystemShopMapper scSystemShopMapper;
    @Autowired
    private ISysDepartService sysDepartService;
    @Resource
    private ISysUserDepartService sysUserDepartService;
    @Resource
    private ISysUserService iSysUserService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param scSystemShop
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "sc_system_shop-分页列表查询")
    @ApiOperation(value = "sc_system_shop-分页列表查询", notes = "sc_system_shop-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ScSystemShop scSystemShop, String startTime, String endTime,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest req) {
        String mianji = req.getParameter("mianji");
        String cityName = req.getParameter("cityName");
        String city = req.getParameter("city");
        String userId = req.getParameter("userId");
        String keyCustomers = req.getParameter("keyCustomers");
        String createTimeBegin = req.getParameter("createTimeBegin");
        String createTimeEnd = req.getParameter("createTimeEnd");
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (StringUtils.isNotBlank(city)) {
            scSystemShop.setCity(cityName);
        } else {
            String ids = null;
            SysUser sysUser = iSysUserService.getById(user.getId());
            String citys = sysUser.getCitys();
            if (StringUtils.isNotBlank(citys)) {
                String[] split = citys.split(",");
                ids = String.join(",", split);
            }
            List<Map<String, Object>> maps = scSystemShopMapper.selectCityData(-1, 1, ids);
            cityName = maps.get(0).get("label").toString();
            scSystemShop.setCity(cityName);
        }
        scSystemShop.setCreateTime(null);
        if (StringUtils.isNotBlank(scSystemShop.getTitle())) {
            scSystemShop.setTitle(null);
        }
        scSystemShop.setAddress(null);
        QueryWrapper<ScSystemShop> queryWrapper = QueryGenerator.initQueryWrapper(scSystemShop, null);
        if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
            startTime = startTime + " 00:00:00";
            endTime = endTime + " 23:59:59";
            queryWrapper.ge(true, "contact_time", startTime);
            queryWrapper.le(true, "contact_time", endTime);
        }
        if (StringUtils.isNotBlank(mianji)) {
            String[] split = mianji.split("-");
            queryWrapper.ge(true, "area_num", split[0]);
            queryWrapper.le(true, "area_num", split[1]);
        }
        if (StringUtils.isNotBlank(createTimeBegin) && StringUtils.isNotBlank(createTimeEnd)) {
            // String[] split = mianji.split("-");
            queryWrapper.ge(true, "create_time", createTimeBegin);
            queryWrapper.le(true, "create_time", createTimeEnd);
        }
        String title = req.getParameter("title");
        if (StringUtils.isNotBlank(title)) {
            queryWrapper.like(true, "title", title);
        }
        if (StringUtils.isNotBlank(keyCustomers) && keyCustomers.equals(1)) {
            queryWrapper.eq("contact_id", user.getId());
        }
        Integer iscontact = scSystemShop.getIsContact() != null ? scSystemShop.getIsContact() : 0;
        if (user.getUserIdentity() == 1 && iscontact == 1) {
            queryWrapper.eq("user_id", user.getId());
        }
        String userId1 = StringUtils.isNotBlank(scSystemShop.getUserId()) ? scSystemShop.getUserId() : null;
        if (user.getUserIdentity() == 2 && StringUtils.isNotBlank(userId1)) {
            queryWrapper.eq("user_id", scSystemShop.getUserId());
        }
        String address = req.getParameter("address");
        if (StringUtils.isNotBlank(address)) {
            queryWrapper.like(true, "address", address).or().like(true, "area", address).or().like(true, "ranges",
                    address);
        }
        String uname = req.getParameter("uname");
        if (StringUtils.isNotBlank(uname)) {
            queryWrapper.like(true, "uname", uname);

        }
        String phone = req.getParameter("phone");
        if (StringUtils.isNotBlank(phone)) {
            queryWrapper.like(true, "phone", phone);
        }
        String dt = req.getParameter("dt");
        if (StringUtils.isNotBlank(dt)) {
            queryWrapper.eq("state", 200);
            queryWrapper.like(true, "contact_time", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
        }
        String tt = req.getParameter("isContact");
        String state = req.getParameter("state");
        if (StringUtils.isNotBlank(keyCustomers) && "1".equals(keyCustomers)) {// 重点客户
            queryWrapper.orderBy(true, false, "create_time");
            queryWrapper.orderBy(true, true, "number");
        } else if (StringUtils.isNotBlank(tt) && "0".equals(tt)) {// 更新数据
            queryWrapper.orderBy(true, false, "create_time");
        } else if ("200".equals(state) || StringUtils.isNotBlank(dt) || "1".equals(tt)) {// 商铺公海，今日新增，已联系
            queryWrapper.orderBy(true, false, "contact_time");
        } else {// 全部店铺
            queryWrapper.orderBy(true, false, "create_time");
        }

        Page<ScSystemShop> page = new Page<ScSystemShop>(pageNo, pageSize);
        IPage<ScSystemShop> pageList = scSystemShopService.page(page, queryWrapper);
        if (scSystemShop.getIsContact() != null && scSystemShop.getIsContact() == 1) {
            List<SysUser> list = iSysUserService.list();
            JSONObject object = new JSONObject();
            for (int i = 0; i < list.size(); i++) {
                object.put(list.get(i).getId(), list.get(i).getRealname());
            }
            for (int i = 0; i < pageList.getRecords().size(); i++) {
                if (StringUtils.isNotBlank(pageList.getRecords().get(i).getUserId())) {
                    pageList.getRecords().get(i)
                            .setRealName(object.getString(pageList.getRecords().get(i).getUserId()));
                }
            }
        }

        return Result.OK(pageList);

    }

    @AutoLog(value = "sc_system_shop-统计更新信息")
    @ApiOperation(value = "sc_system_shop-统计更新信息", notes = "sc_system_shop-统计更新信息")
    @GetMapping(value = "/tongji")
    public Result<?> tongji(String userId, String startTime, String endTime, String cityName, String area,
            HttpServletRequest req) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        JSONObject object = new JSONObject();
        if (user.getId().equals("1454463127583854594")) {
            QueryWrapper<ScSystemShop> queryWrapper1 = new QueryWrapper<>();
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper1.eq("user_id", userId);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper1.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper1.eq("area", area);
            }
            queryWrapper1.eq("is_contact", "1");
            queryWrapper1.isNotNull("contact_time");
            queryWrapper1.isNotNull("user_id");
            Integer total = scSystemShopMapper.selectCount(queryWrapper1);// 总数

            QueryWrapper<ScSystemShop> queryWrapper4 = new QueryWrapper<>();
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper4.eq("user_id", userId);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper4.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper4.eq("area", area);
            }
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper4.ge(true, "contact_time", startTime);
                queryWrapper4.le(true, "contact_time", endTime);
            }
            queryWrapper4.eq("is_contact", "1");
            queryWrapper4.isNotNull("contact_time");
            queryWrapper4.isNotNull("user_id");
            Integer time = scSystemShopMapper.selectCount(queryWrapper4);// 时间段更新
            String times = "-";
            if (StringUtils.isNotBlank(startTime)) {
                times = startTime + "至" + endTime + "共更新:" + time;
            }

            QueryWrapper<ScSystemShop> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.like(true, "contact_time", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
            queryWrapper2.eq("is_contact", "1");
            queryWrapper2.isNotNull("contact_time");
            queryWrapper2.isNotNull("user_id");
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper2.eq("user_id", userId);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper2.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper2.eq("area", area);
            }
            Integer today = scSystemShopMapper.selectCount(queryWrapper2);// 日更新

            QueryWrapper<ScSystemShop> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.like(true, "contact_time", DateUtils.formatDate(new Date(), "yyyy-MM"));
            queryWrapper3.eq("is_contact", "1");
            queryWrapper3.isNotNull("contact_time");
            queryWrapper3.isNotNull("user_id");
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper3.eq("area", area);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper3.eq("city", cityName);
            }
            queryWrapper3.eq("is_contact", "1");
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper3.eq("user_id", userId);
            }
            Integer month = scSystemShopMapper.selectCount(queryWrapper3);// 月更新
            object.put("total", total);
            object.put("today", today);
            object.put("month", month);
            object.put("time", times);
        } else {
            userId = user.getId();
            QueryWrapper<ScSystemShop> queryWrapper1 = new QueryWrapper<>();
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper1.eq("user_id", userId);
            }
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                queryWrapper1.ge(true, "contact_time", startTime);
                queryWrapper1.le(true, "contact_time", endTime);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper1.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper1.eq("area", area);
            }
            queryWrapper1.eq("is_contact", "1");
            queryWrapper1.isNotNull("contact_time");
            queryWrapper1.isNotNull("user_id");
            Integer total = scSystemShopMapper.selectCount(queryWrapper1);// 总数

            QueryWrapper<ScSystemShop> queryWrapper4 = new QueryWrapper<>();
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper4.eq("user_id", userId);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper4.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper4.eq("area", area);
            }
            if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
                startTime = startTime + " 00:00:00";
                endTime = endTime + " 23:59:59";
                queryWrapper4.ge(true, "contact_time", startTime);
                queryWrapper4.le(true, "contact_time", endTime);
            }
            queryWrapper4.eq("is_contact", "1");
            queryWrapper4.isNotNull("contact_time");
            queryWrapper4.isNotNull("user_id");
            Integer time = scSystemShopMapper.selectCount(queryWrapper4);// 时间段更新
            String times = "-";
            if (StringUtils.isNotBlank(startTime)) {
                times = startTime + "至" + endTime + "共更新:" + time;
            }

            QueryWrapper<ScSystemShop> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.like(true, "contact_time", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
            queryWrapper2.eq("is_contact", "1");
            queryWrapper2.isNotNull("contact_time");
            queryWrapper2.isNotNull("user_id");
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper2.eq("user_id", userId);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper2.eq("city", cityName);
            }
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper2.eq("area", area);
            }
            Integer today = scSystemShopMapper.selectCount(queryWrapper2);// 日更新

            QueryWrapper<ScSystemShop> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.like(true, "contact_time", DateUtils.formatDate(new Date(), "yyyy-MM"));
            queryWrapper3.eq("is_contact", "1");
            queryWrapper3.isNotNull("contact_time");
            queryWrapper3.isNotNull("user_id");
            if (org.springframework.util.StringUtils.hasText(area)) {
                queryWrapper3.eq("area", area);
            }
            if (org.springframework.util.StringUtils.hasText(cityName)) {
                queryWrapper3.eq("city", cityName);
            }
            queryWrapper3.eq("is_contact", "1");
            if (org.springframework.util.StringUtils.hasText(userId)) {
                queryWrapper3.eq("user_id", userId);
            }
            Integer month = scSystemShopMapper.selectCount(queryWrapper3);// 月更新
            object.put("total", total);
            object.put("today", today);
            object.put("month", month);
            object.put("time", times);
        }

        return Result.OK(object);
    }

    @AutoLog(value = "行业")
    @GetMapping(value = "/selectHangye")
    public Result<?> selectHangye() {
        List<Map<String, Object>> maps = new ArrayList<>();
        if (redisUtil.hasKey("Hangye")) {
            maps = (List) redisUtil.lGet("Hangye", 0, -1);
        } else {
            maps = scSystemShopMapper.selectHangye();
            redisUtil.lSet("Hangye", maps);
        }
        return Result.OK(maps);
    }

    @AutoLog(value = "城市")
    @GetMapping(value = "/selectCityData")
    public Result<?> selectCityData(@RequestParam(name = "parentId") Integer parentId,
            @RequestParam(name = "level") Integer level,
            @RequestParam(name = "type", required = false) Integer type,
            HttpServletRequest req) {
        List<Map<String, Object>> maps = getCity(parentId, level, type);
        return Result.OK(maps);
    }

    @AutoLog(value = "统计")
    @GetMapping(value = "/getCount")
    public Result<?> getCount(
            HttpServletRequest req) {
        QueryWrapper<ScSystemShop> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "key_customers", "1");
        Integer keyc = scSystemShopMapper.selectCount(queryWrapper);

        QueryWrapper<ScSystemShop> queryWrapper1 = new QueryWrapper<>();
        Integer total = scSystemShopMapper.selectCount(queryWrapper1);

        QueryWrapper<ScSystemShop> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.like(true, "create_time", DateUtils.formatDate(new Date(), "yyyy-MM-dd"));
        Integer today = scSystemShopMapper.selectCount(queryWrapper2);

        return Result.OK(new Integer[] { today, total, keyc });
    }

    private List<Map<String, Object>> getCity(Integer parentId, Integer level, Integer type) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String ids = null;
        if (type == null && level == 1) {
            SysUser sysUser = iSysUserService.getById(user.getId());
            String citys = sysUser.getCitys();
            if (StringUtils.isNotBlank(citys)) {
                String[] split = citys.split(",");
                ids = String.join(",", split);
            }
        }
        List<Map<String, Object>> maps = scSystemShopMapper.selectCityData(parentId, level, ids);
        return maps;
    }

    /**
     * 添加
     *
     * @param scSystemShop
     * @return
     */
    @AutoLog(value = "sc_system_shop-添加")
    @ApiOperation(value = "sc_system_shop-添加", notes = "sc_system_shop-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ScSystemShop scSystemShop) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        scSystemShop.setState(200);
        scSystemShop.setIsContact(1);
        scSystemShop.setContactTime(new Date());
        scSystemShop.setUserId(user.getId());
        scSystemShopService.save(scSystemShop);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param scSystemShop
     * @return
     */
    @AutoLog(value = "sc_system_shop-编辑")
    @ApiOperation(value = "sc_system_shop-编辑", notes = "sc_system_shop-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ScSystemShop scSystemShop) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (scSystemShop.getIsContact() != null && scSystemShop.getIsContact().intValue() == 1) {
            scSystemShop.setContactTime(new Date());
            // scSystemShop.setCreateTime(new Date());
            scSystemShop.setUserId(user.getId());
        }
        if (scSystemShop.getKeyCustomers().equals(1)) {
            scSystemShop.setContactId(user.getId());
        } else {
            scSystemShop.setContactId("");
        }
        scSystemShopMapper.updateShoInfo(scSystemShop);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "sc_system_shop-通过id删除")
    @ApiOperation(value = "sc_system_shop-通过id删除", notes = "sc_system_shop-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        scSystemShopService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "sc_system_shop-批量删除")
    @ApiOperation(value = "sc_system_shop-批量删除", notes = "sc_system_shop-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.scSystemShopService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "sc_system_shop-通过id查询")
    @ApiOperation(value = "sc_system_shop-通过id查询", notes = "sc_system_shop-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ScSystemShop scSystemShop = scSystemShopService.getById(id);
        if (scSystemShop == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(scSystemShop);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param scSystemShop
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ScSystemShop scSystemShop) {
        return super.exportXls(request, scSystemShop, ScSystemShop.class, "sc_system_shop");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ScSystemShop.class);
    }

}
